package com.atguigu.day09;

import com.atguigu.utils.LoginEvent;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.cep.CEP;
import org.apache.flink.cep.PatternSelectFunction;
import org.apache.flink.cep.PatternStream;
import org.apache.flink.cep.pattern.Pattern;
import org.apache.flink.cep.pattern.conditions.SimpleCondition;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

import java.util.List;
import java.util.Map;

// 使用Flink CEP检测用户连续三次登录失败
public class Example1 {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env =
                StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        SingleOutputStreamOperator<LoginEvent> stream = env
                .fromElements(
                        new LoginEvent("user-1", "fail", 1000L),
                        new LoginEvent("user-1", "fail", 2000L),
                        new LoginEvent("user-2", "success", 3000L),
                        new LoginEvent("user-1", "fail", 4000L),
                        new LoginEvent("user-1", "fail", 5000L)
                )
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy.<LoginEvent>forMonotonousTimestamps()
                                .withTimestampAssigner(new SerializableTimestampAssigner<LoginEvent>() {
                                    @Override
                                    public long extractTimestamp(LoginEvent element, long recordTimestamp) {
                                        return element.ts;
                                    }
                                })
                );

        // 定义检测模板
        Pattern<LoginEvent, LoginEvent> pattern = Pattern
                // 模板中的事件类型是LoginEvent
                // begin表示模板中的第一个事件，取名字为`first`
                .<LoginEvent>begin("first")
                // 表示事件需要满足什么样的条件
                .where(new SimpleCondition<LoginEvent>() {
                    @Override
                    public boolean filter(LoginEvent value) throws Exception {
                        return value.type.equals("fail");
                    }
                })
                // next表示second事件必须紧跟在first事件后面
                .next("second")
                // `second`事件需要满足的条件
                .where(new SimpleCondition<LoginEvent>() {
                    @Override
                    public boolean filter(LoginEvent value) throws Exception {
                        return value.type.equals("fail");
                    }
                })
                // next表示third事件必须紧跟在second事件的后面
                .next("third")
                // `third`需要满足的条件
                .where(new SimpleCondition<LoginEvent>() {
                    @Override
                    public boolean filter(LoginEvent value) throws Exception {
                        return value.type.equals("fail");
                    }
                });

        // 在流上根据模板来匹配连续三次登录失败
        // patternStream就是匹配到的结果组成的数据流
        PatternStream<LoginEvent> patternStream = CEP.pattern(
                // 待匹配的流，注意别忘了keyBy
                stream.keyBy(r -> r.userId),
                // 定义的模板
                pattern
        );

        // 将匹配到的结果选择出来
        SingleOutputStreamOperator<String> result = patternStream
                .select(new PatternSelectFunction<LoginEvent, String>() {
                    @Override
                    public String select(Map<String, List<LoginEvent>> pattern) throws Exception {
                        // {
                        //    "first": List<LoginEvent> // List中只有一个元素
                        //    "second": List
                        //    "third": List
                        // }
                        LoginEvent first = pattern.get("first").get(0);
                        LoginEvent second = pattern.get("second").get(0);
                        LoginEvent third = pattern.get("third").get(0);
                        String result = "用户" + first.userId + "在时间戳：" +
                                "" + first.ts + ";" + second.ts + ";" +
                                "" + third.ts + ";连续三次登录失败!";
                        // result就是要发送到下游的字符串
                        return result;
                    }
                });

        result.print();

        env.execute();
    }
}
